import React, { Component } from 'react';

class ScrollListener extends Component {
  constructor(props) {
    super(props);
    this.divElement = null;
  }

  componentDidMount() {
    this.divElement = document.getElementById(this.props.elementId);
    
    if (!this.divElement) {
      console.warn(`Element with id "${this.props.elementId}" not found.`);
      return;
    }
    
    // 初始检查
    this.checkScrollPosition();
    
    // 添加滚动事件监听器
    this.divElement.addEventListener('scroll', this.handleScroll);
  }

  componentWillUnmount() {
    // 组件卸载时移除监听器
    if (this.divElement) {
      this.divElement.removeEventListener('scroll', this.handleScroll);
    }
  }

  handleScroll = () => {
    this.checkScrollPosition();
  };

  checkScrollPosition = () => {
    if (!this.divElement) return;
    
    const threshold = this.props.threshold || 1;
    const isAtBottom = 
      this.divElement.scrollHeight - this.divElement.scrollTop <= 
      this.divElement.clientHeight + threshold;
      
    // 调用父组件的回调函数
    if (typeof this.props.onScrollBottom === 'function') {
      this.props.onScrollBottom(isAtBottom);
    }
  };

  render() {
    return null; // 不需要渲染任何内容
  }
}

export default ScrollListener;